package com.kgc.schedule;

import com.alibaba.dubbo.config.annotation.Reference;
import com.kgc.api.goods.HotWordApi;
import com.kgc.bean.HotWord;
import com.kgc.constant.ElsConstant;
import com.kgc.util.RedisUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import sun.tools.jar.Main;

import java.util.Iterator;
import java.util.Set;

/**
 * Created on 2021/6/21.
 * Author: lzy
 * Description: redis同步到数据库，并删除缓存
 */
@Component
@Slf4j
public class AsycRedisHotWordSchedule {

    @Autowired
    private RedisUtils redisUtils;

    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Reference(timeout = 30000)
    private HotWordApi hotWordApi;


    /**
    *@ClassName: AsycRedisHotWordSchedule
    *@Description 测试的时候每30分钟Redis的hotword数据保存到数据库
    *@Author lzy
    *@Date 2021/6/21
    */
    //@Scheduled(cron = " 0 0 0 1/1 * ?  ")
    // @Scheduled(cron = "0 0/30 * * * ? ")
    @Scheduled(fixedDelay = 60*1000)
    public void asyncRedisHotWord(){
        // 获取Redis里的热词数据
        Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisTemplate.opsForZSet().reverseRangeWithScores(ElsConstant.HOT_WORD_DATABASE, 0, -1);

        Iterator<ZSetOperations.TypedTuple<Object>> iterator = typedTuples.iterator();
        // 存入热词数据，并覆盖相同数据
       while (iterator.hasNext()){
           ZSetOperations.TypedTuple<Object> next = iterator.next();
           log.info("当前的key的值为：{}",next.getValue());
           // 根据热词去数据库查询
           HotWord hotWordCheck= hotWordApi.querySelectHotWord((String)next.getValue());
           // log.info("通过key查询的数据的id值：{}",hotWordCheck.getId());
           // log.info("通过key查询的数据的搜索量值：{}",hotWordCheck.getHotWordCount());
           int score = (int) next.getScore().doubleValue();
           // log.info("redis获取的搜索量：{}",score);
           HotWord hotWord = new HotWord();
           hotWord.setHotWord((String) next.getValue());

           // 判断数据库是否存在 true 不是空的
           if(!StringUtils.isEmpty(hotWordCheck.getId())){
               hotWord.setId(hotWordCheck.getId());
               int num = score + hotWordCheck.getHotWordCount();
               hotWord.setHotWordCount(num);
              if( hotWordApi.queryUpdateCordToHotWord(hotWord)){
                  log.info("Redis热词数据更新到数据库成功！");
                  // 清空Redis缓存
                  //redisTemplate.opsForZSet().remove(ElsConstant.HOT_WORD_DATABASE,hotWord);
                  redisTemplate.opsForZSet().removeRange(ElsConstant.HOT_WORD_DATABASE, 0, -1);
              }else {
                  log.error("Redis添加数据库失败-1");
              }
           }else {
               // 更新热词到数据库，如果查出为空，那么就添加到数据库
               hotWord.setHotWordCount(score);
               if(hotWordApi.queryAddNewHotWord(hotWord)){
                   log.info("数据库库成功添加一条热词数据，热词为：{}，搜索量为：{}",hotWord.getHotWord(),hotWord.getHotWordCount());
                   // 清空Redis缓存
                   //redisTemplate.opsForZSet().remove(ElsConstant.HOT_WORD_DATABASE,hotWord);
                   redisTemplate.opsForZSet().removeRange(ElsConstant.HOT_WORD_DATABASE, 0, -1);
               }else {
                   log.error("Redis添加数据库失败-2");
               }
           }
       }





    }






}
